import 'package:dio/dio.dart';
import 'package:f_enjoy_plus/core/constants/app_colors.dart';
import 'package:f_enjoy_plus/components/Header.dart';
import 'package:f_enjoy_plus/utils/http.dart';
import 'package:f_enjoy_plus/utils/loadImage.dart';
import 'package:f_enjoy_plus/utils/toast.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  ProfilePage({super.key, required this.userInfo});

  final userInfo;

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  Map userInfo = {"avatar": "", "nickName": ""};
  final _nickNameController = TextEditingController();

  @override
  void initState() {
    super.initState();
    setState(() {
      userInfo = widget.userInfo;
      _nickNameController.text = userInfo['nickName'] ?? '';
    });
  }

  updateNickName() async {
    try {
      final res = await http.put(
        '/userInfo',
        data: {'nickName': userInfo['nickName']},
      );
      ToastUtils.success('修改成功');
      print(res);
    } catch (e) {
      print(e);
    }
  }

  updateAvatar(String path) async {
    try {
      FormData fd = FormData.fromMap({
        'avatar': MultipartFile.fromFileSync(path, filename: 'avatar.jpg'),
        'type': 'avatar',
      });
      final res = await http.post('/upload', fd);
      setState(() {
        userInfo['avatar'] = res['url'];
        ToastUtils.success('修改成功');
      });
      print('path: $path');
    } catch (e) {
      print(e);
      ToastUtils.error('修改失败 $e');
    } finally {
      Navigator.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: Header(
        title: '个人信息',
        onBack: () {
          print('object');
          Navigator.pop(context);
        },
      ),
      body: Container(
        padding: EdgeInsets.all(16),
        child: Column(
          children: [
            Row(
              children: [
                Text('头像'),
                Spacer(),
                GestureDetector(
                  onTap: () {
                    LoadImageUtils.showImagePickerBottomSheet(
                      context: context,
                      title: '修改头像',
                      onImageSelected: (path, dialogContext) async {
                        await updateAvatar(path);
                        Navigator.pop(dialogContext);
                      },
                    );
                  },
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(16),
                    child:
                        userInfo['avatar'] != ''
                            ? Image.network(
                              userInfo['avatar'],
                              width: 32,
                              height: 32,
                            )
                            : Image.asset(
                              'assets/images/avatar_1.jpg',
                              width: 32,
                              height: 32,
                            ),
                  ),
                ),
              ],
            ),
            SizedBox(height: 16),
            Row(
              children: [
                Text('昵称'),
                Spacer(),
                Expanded(
                  child: TextField(
                    controller: _nickNameController,
                    maxLength: 12,
                    decoration: InputDecoration(
                      hintText: '请输入昵称',
                      hintStyle: TextStyle(
                        color: AppColors.textSecondary,
                        fontSize: 14,
                      ),
                      border: InputBorder.none,
                    ),
                    textAlign: TextAlign.right,
                    onChanged: (value) {
                      setState(() {
                        userInfo['nickName'] = value;
                      });
                    },
                    onEditingComplete: () {
                      updateNickName();
                    },
                  ),
                ),
              ],
            ),
            SizedBox(height: 32),
            ElevatedButton(
              onPressed: () {
                updateNickName();
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: AppColors.primary,
                minimumSize: Size(double.infinity, 50),
              ),
              child: Text(
                '保存',
                style: TextStyle(color: AppColors.white, fontSize: 16),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
